function getSubOptions(editFlag) {
    var initOptions = {
        idField: 'cid',
        fitColumns: false,
        width: 1700,
        checkOnSelect: false,
        singleSelect: false,
        fit: false,
        columns: [[{
            checkbox: true
        }, {
            field: 'subApplicationNumber',
            title: '采购申请子项号',
            width: 110
        }, {
            title: '子项状态',
            field: 'statusSub',
            width: 80
        }, {
            title: '件数',
            field: 'numberPage',
            width: 60,
            editor: {
                type: 'numberbox'
            }
        }, {
            field: 'weight',
            title: '<label class="redSharp">*重量</label>',
            width: 60,
            editor: {
                type: 'numberbox',
                options: {
                    precision:6,
                    required: true,
                    validType: 'noEmptyNumber'
                }
            },
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatWeight(value);
            }
        }, {
            field: 'unitPrice',
            title: '<label class="redSharp">*单价(含税)</label>',
            width: 80,
            editor: {
                type: 'numberbox',
                options: {
                    precision: 2,
                    required: true,
                    validType: 'noEmptyNumber'
                }
            },
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'paymentAmount',
            title: '货款金额',
            width: 80,
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'f_pm_id',
            title: '<label class="redSharp">*品名</label>',
            width: 130,
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return rowData.goodsName;
            },
            editor: {
                type: 'combotree',
                options: {
                    required: true,
                    data: treeData,
                    textField: 'text',
                    onlyLeafCheck: true,
                    onBeforeSelect: function (node) {
                        var t = $(this).tree;
                        var isLeaf = t('isLeaf', node.target);
                        if (!isLeaf) {//选择的不是叶子节点
                            return false;
                        }
                    },
                    onClick:function(node){  //处理双击事件
                        var $this = $(this);
                        var target = node.target;
                        if( $this.tree('getChildren',target).length ){ //只对有子节点的节点做处理
                            $this.tree("toggle",target);
                            //黑魔法
                            $('td>.combo>span>span').click();
                        }
                    },
                    onHidePanel: function (node) {
                    }
                }
            }
        }, {
            field: 'marks',
            title: '<label class="redSharp">*牌号</label>',
            width: 60,
            editor: {
                type: 'validatebox',
                options: {
                    required: true
                }
            }
        }, {
            field: 'cpspecification',
            title: '<label class="redSharp">*规格</label>',
            width: 100,
            editor: {
                type: 'validatebox',
                options: {
                    required: true
                }
            }
        }, {
            field: 'f_cd_id',
            title: '<label class="redSharp">*产地</label>',
            width: 60,
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                for (var i = 0; i < address.length; i++) {
                    if (address[i].id == value) {
                        return address[i].orName;
                    }
                }
            },
            editor: {
                type: 'combobox',
                options: {
                    required: true,
                    data: address,
                    valueField: 'id',
                    textField: 'orName',
                    editable: false
                }
            }
        }, {
            field: 'standards',
            title: '技术标准',
            width: 60,
            editor: {
                type: 'text'
            }
        }, {
            field: 'qualityGrade',
            title: '质量等级',
            width: 60,
            editor: {
                type: 'text'
            }
        }, {
            field: 'unitWeight',
            title: '件重',
            width: 40,
            editor: {
                type: 'numberbox',
                options: {
                    precision:6
                }
            },
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatWeight(value);
            }
        }, {
            field: 'totalCost',
            title: '金额总计',
            width: 80,
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'deliveryMethod',
            title: '*交货方式',
            width: 60,
            editor: {
                type: 'validatebox',
                options: {
                    required: true
                }
            }
        }, {
            field: 'subtaxAmount',
            width: 80,
            title: '税额',
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'taxRate',
            width: 40,
            title: '税率',
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'qualityNum',
            title: '质保书份数',
            width: 70,
            editor: {
                type: 'text'
            }
        }, {
            field: 'appSubContract',
            title: '供应商合同子项号',
            width: 110,
            editor: {
                type: 'text'
            }
        }, {
            field: 'resourceNumber',
            title: '资源号',
            width: 60,
            editor: {
                type: 'text'
            }
        }, {
            field: 'remark',
            title: '备注',
            width: 60,
            editor: {
                type: 'text'
            }
        }, {
            hidden:'true',
            field: 'cdName',
            title: '产地名称'
        }, {
            hidden:'true',
            field: 'goodsName',
            title: '品种名称'
        }]],
        toolbar: [{
            id: "addSub",
            text: '新增子项',
            iconCls: 'icon-add',
            handler: function () {
                add();
            }
        }, '-', {
            id: "deleteSub",
            text: '删除子项',
            iconCls: 'icon-remove',
            handler: function () {
                del();
            }
        }],
        onClickCell: onClickCell,
        onAfterEdit: function (rowIndex, rowData, changes) {
            calculateSub(rowIndex, rowData);
            calculateToTop();
        }
    }
    if(!editFlag){
        initOptions.columns[0][1].hidden = 'true';
    }
    return initOptions;
}

function onClickCell(index, field) {
    if (endEditing($('#subItem'))) {
        if (checkLineStatus($('#subItem'), index)) {
            $('#subItem').datagrid('selectRow', index)
                .datagrid('editCell', {index: index, field: field});
            var ed = $('#subItem').datagrid('getEditor', {index: index, field: field});
            if (ed && ed.target) {
                $(ed.target).focus();
            }
            editIndex = index;
        }
    }
}
function checkLineStatus(node, index) {
    var rows = node.datagrid('getRows');
    if (rows && rows[index]) {
        if (!rows[index].statusSub) {
            return true;
        }
        return !(rows[index].statusSub != "新增" && rows[index].statusSub != "审批不通过");
    }
}

////货款金额等于重量*单价（含税），金额总计等于货款金额+运杂费，税率取系统配置项
function calculateSub(rowIndex, rowData) {
    // 得到columns对象
    var columns = $('#subItem').datagrid("options").columns;
// 得到rows对象
    var rows = $('#subItem').datagrid("getRows"); // 这段代码是// 对某个单元格赋值
    var payMoney = (rowData.weight ? rowData.weight : 0) * (rowData.unitPrice ? rowData.unitPrice : 0);
    rows[rowIndex][columns[0][getColumnIndex(columns[0], "paymentAmount")].field] = payMoney.toFixed(2);

    //为运杂费预留
    rows[rowIndex][columns[0][getColumnIndex(columns[0], "totalCost")].field] = parseFloat(payMoney.toFixed(2));
    //税额
    var subtaxAmount = calculateTax(payMoney, rowData.taxRate);
    rows[rowIndex][columns[0][getColumnIndex(columns[0], "subtaxAmount")].field] = parseFloat(subtaxAmount.toFixed(2));
    //产地
    rows[rowIndex][columns[0][getColumnIndex(columns[0], "cdName")].field] = getComboboxText(address, rowData.f_cd_id);
    //品名
    if (rowData.f_pm_id) {
        rows[rowIndex][columns[0][getColumnIndex(columns[0], "goodsName")].field] = getComboTreeText(treeData, rowData.f_pm_id);
    }

// 刷新该行, 只有刷新了才有效果
    $('#subItem').datagrid('refreshRow', rowIndex);
}

var heTongStatus = getStatusData("/global/status.html");
function prepareApplicationSubmitPostData(flag) {
    endEditing($('#subItem'));
    var applicationData = {};
    var postData = $('#searchForm-small').serializeJson();
    //状态码
    postData.status = changeStatusVal($('#status').val(), heTongStatus);
    if (flag == undefined) {
        //签约用户姓名
        var userNameRow = $('#userName').combogrid('grid').datagrid('getSelected');
        //商户代码 商户名称
        var menberNoRow = $('#memberNo').combogrid('grid').datagrid('getSelected');
        postData.userName = userNameRow.trueName;
        postData.providerName = menberNoRow.memberName;
        postData.providerCode = menberNoRow.memberNo;
    } else {
        postData.id = $('#applicationId').text();
    }
    postData.contractDate = $('#contractDate').datebox("getText");
    //子项表数据
    var subRows = getUsefulRows($('#subItem').datagrid('getRows'));

    //数据主体结构
    applicationData.application = postData;
    applicationData.applicationSubList = subRows;
    return applicationData;
}

function prepareApplicationSubmitRealPostData(flag) {
    var data = prepareApplicationSubmitPostData(flag);
    $.each(data.applicationSubList, function (index, value) {
        value.statusSub = changeStatusVal(value.statusSub, heTongStatus);
        delete value.cid;
    });
    return data;
}

//10、点击“提交”按钮，采购申请状态置为“提交”。
//11、点击“撤销提交”按钮，采购申请状态置为“新增”。
//12、点击“撤销”按钮，采购申请状态置为“撤销”。
//13、撤销状态的采购申请不能进行任何操作。
//14、新增状态的采购申请可以新增子项、删除子项、提交、撤销、保存。
//15、提交状态的采购申请可以撤销提交。
//16、生成采购合同状态的采购申请不能进行任何操作。
//17、审批不通过状态的采购申请可以新增子项、删除子项、提交、撤销、保存。
function setApplicationAddButtonsStatus(status) {
    var nodeArray = [$("#addSub"), $("#deleteSub"), $("#editFunction"),
        $("#submitFunction"), $("#cancelSubmitFunction"), $("#cancelFunction")];
    if (status === "撤销" || status === "生成采购合同") {
        setLinkButtonStatus(nodeArray, [0, 0, 0, 0, 0, 0]);
    } else if (status === "新增" || status === "审批不通过") {
        setLinkButtonStatus(nodeArray, [1, 1, 1, 1, 0, 1]);
    } else if (status === "提交") {
        setLinkButtonStatus(nodeArray, [0, 0, 0, 0, 1, 0]);
    }
}

//刷新采购申请页面
function refreshApplicationPage(data) {
    //上部init
    loadData(data.object.application);
    $('#totalAmount').numberbox('setValue',data.object.application.totalAmount);
    $('#totalWeight').numberbox('setValue',data.object.application.totalWeight);
    $('#taxGoodsAmount').numberbox('setValue',data.object.application.taxGoodsAmount);
    $('#taxAmount').numberbox('setValue',data.object.application.taxAmount);
    $('#contractDate').datebox({
        required: true,
        editable: false
    });
    $('#contractDate').datebox("setValue", data.object.application.contractDate);
    //下部init
    var options = getSubOptions(true);
    options.data = data.object.applicationSubList;
    $.each(options.data, function (index, value) {
        value.cid = UUID();
    })
    initDataGridNoPager($('#subItem'), options);
    setApplicationAddButtonsStatus(data.object.application.status);
}

function getApplicationDetail(data) {
    parent.$.modalDialog.handler.dialog('close');
    var options = {"id": data.object.application.id};
    editApplicationFunction(options);
}

//为$('#subItem') 增加子项
function add() {
    $('#subItem').datagrid('uncheckAll');
    var row = {
        cid: UUID(),
        deliveryMethod: "自提",
        numberPage: "1.00",
        taxRate: "0.17",
        statusSub: "新增"
    };
    $('#subItem').datagrid('appendRow', row);
    $('#subItem').datagrid('checkRow', $('#subItem').datagrid('getRows').length - 1);
}

//删除子项
function del() {
    var rows = $('#subItem').datagrid('getChecked');
    var cunzaiIds = [];
    var ids = [];
    if (rows.length > 0) {
        $.each(rows, function (index, value) {
            if (value.id) {
                cunzaiIds.push(value.id);
            }
            ids.push(value.cid);
        });
        if (cunzaiIds.length > 0) {
            $.messager.confirm('请确认', '您要删除当前所选项目,子项全部删除合同将被撤销？', function (r) {
                if (r) {
                    var postData = {
                        'applicationId': $("#applicationId").text(),
                        'applicationSubIds': cunzaiIds
                    }
                    postAjax("/purchase/deleteOneApplicationSub.html", JSON.stringify(postData),
                        refreshApplicationPage);
                    calculateToTop();
                }
            });
        } else if (ids.length > 0) {
            $.messager.confirm('请确认', '您要删除当前所选项目？', function (r) {
                if (r) {
                    $.each(ids, function (index, value) {
                        $('#subItem').datagrid('deleteRow', $('#subItem').datagrid('getRowIndex', value));
                    });
                    calculateToTop();
                }
            });
        } else {
            $.messager.alert('提示', '请选择要删除的记录！', 'error');
        }
    }
}
